package ch.ethz.eai.facade;

import java.rmi.RemoteException;
import java.util.LinkedList;

import org.apache.axis2.AxisFault;

import ch.ethz.eai.data.Location;
import ch.ethz.eai.data.PointOfInterest;

import net.virtualearth.dev.webservices.v1.search.ISearchService_Search_ResponseSummaryFault_FaultMessage;
import net.virtualearth.dev.webservices.v1.search.SearchServiceStub;
import net.virtualearth.dev.webservices.v1.search.SearchServiceStub.Credentials;
import net.virtualearth.dev.webservices.v1.search.SearchServiceStub.Search;
import net.virtualearth.dev.webservices.v1.search.SearchServiceStub.SearchRequest;
import net.virtualearth.dev.webservices.v1.search.SearchServiceStub.SearchResultBase;
import net.virtualearth.dev.webservices.v1.search.SearchServiceStub.SearchResultSet;


public class SearchFacade {

	/**
	 * Gets a list of places which have a name that contains the 'type' term.
	 * <br><i>Important: </i>This will work only when we have a full address (street+town+country). 
	 * @param loc
	 * @param type
	 * @return
	 */
	//hint: in case of european cities using addresses close to city centers is better
	public static PointOfInterest[] getPOIs(Location loc, String type) {
		LinkedList<PointOfInterest> resultList = new LinkedList<PointOfInterest>();
		try {
		SearchServiceStub sss = new SearchServiceStub();
		Search s = new Search();
		SearchRequest param = new SearchRequest();
		Credentials cred = new Credentials();
		//super secret key for ms's API
		cred.setToken("AtgDiZ9F17tQlEh5fcSeNQcS5epyZdvbpmiXbJb7j9mCDw5o4-eQSPpv5ckWWIyz");
		param.setCredentials(cred);
		param.setQuery(type+" near "+loc.getStreetAddress()+", "+loc.getTown()+", "+loc.getCountry());
		s.setRequest(param);
		SearchResultSet[] searchRes = sss.search(s).getSearchResult().getResultSets().getSearchResultSet();
		int found = 0;
		for (SearchResultSet  srs : searchRes) {
			if (srs.getResults().getSearchResultBase()!=null) {
				for (SearchResultBase x : srs.getResults().getSearchResultBase()) {
					Location resolvedLoc[] = GeocodeFacade.reverseGeocode(new Location(x.getLocationData().getLocations().getGeocodeLocation()[0].getLongitude(), x.getLocationData().getLocations().getGeocodeLocation()[0].getLatitude()));
					if (resolvedLoc.length>0) {
						PointOfInterest newPoi = new PointOfInterest(resolvedLoc[0], x.getName(), type);
						resultList.add(newPoi);
						found++;
						if (found==5) {
							return resultList.toArray(new PointOfInterest[0]);
						}
					}
				}
			}
		}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList.toArray(new PointOfInterest[0]);
		
	}
	
}
